import React, { ReactNode, useEffect, useReducer } from 'react'
import { useLocation } from 'react-router-dom'
import { ReducerAction } from '../types'

export interface AppStore {
  headerMenuKey: string
}

export interface AppContext {
  appStore: AppStore
  dispatch: React.Dispatch<ReducerAction>
}

const initAppStore: AppStore = {
  headerMenuKey: ''
}

const appContext = React.createContext<AppContext | null>(null)

appContext.displayName = 'AppContext'

const appReducer = (preState: AppStore, action: ReducerAction) => {
  const { type, payload } = action

  switch (type) {
    case 'update': {
      const { key, value } = payload
      return { ...preState, [key]: value }
    }
    default:
      return { ...preState }
  }
}

export const AppProvider = ({ children }: { children: ReactNode }) => {
  const [appStore, dispatch] = useReducer(appReducer, initAppStore)

  const location = useLocation()

  useEffect(() => {
    const firstUrl = location.pathname.split('/')[1]
    dispatch({
      type: 'update',
      payload: { key: 'headerMenuKey', value: firstUrl }
    })
  }, [location])

  return (
    <appContext.Provider value={{ appStore, dispatch }}>
      {children}
    </appContext.Provider>
  )
}

export const useAppContext = () => {
  const context = React.useContext(appContext)
  if (!context) {
    throw new Error('useAppContext必须在AppProvider中使用')
  }
  return context
}
